import {Layout, Menu, theme} from "antd";
import * as Icon from "@ant-design/icons";
import React, {useState} from "react";
import MenuConfig from './siderData'
import {useSelector,useDispatch} from 'react-redux'
import {useNavigate,useLocation } from 'react-router-dom'
import {setTabList,setCurrentTabPath} from "../../store/reducers/tab";


const {Sider} = Layout;

// 动态处理icon

const iconToElement = (name) => React.createElement(Icon[name])

// 处理菜单数据
const items = MenuConfig.map(item => {
    // 没有子菜单
    const child = {
        key: item.path, icon: iconToElement(item.icon), label: item.label
    }
    if (item.children) {
        child.children = item.children.map(item1 => {
            return {
                key: item1.path, icon: iconToElement(item1.icon), label: item1.label
            }
        })
    }
    return child
})


export default ({collapsed}) => {
    const dispatch = useDispatch()
    const location = useLocation();
    const currentPath = location.pathname;

    const redux_collapsed = useSelector(state => state.tab.isCollapse)
    const navigate = useNavigate()
    const selectMenu = (e) => {
        navigate(e.key)
        let data;
        MenuConfig.forEach(item => {
            if (item.path === e.keyPath[e.keyPath.length - 1]) {
                data = item
                if (e.keyPath.length > 1) {
                    data = item.children.find((child) => {
                        return child.path === e.key
                    })
                }
            }
        })
        dispatch(setTabList({data,type:'add'}))
        dispatch(setCurrentTabPath(e.key))
    }


    return (<Sider trigger={null} collapsible collapsed={collapsed}>
        <p className={'System_name'}> {redux_collapsed ? '后台' : '后台管理'} </p>
        <Menu
            theme="dark"
            mode="inline"
            selectedKeys={[currentPath]}
            items={items}
            onClick={selectMenu}
        />
    </Sider>)
}